const { modelName } = require("../models/userModel");
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');


async function addUser(req, res) {
    //新增用户
    let result = await mongoose.model(modelName).create(req.body);
    res.send({
        message: '新增成功',
        code: 200,
        data: result
    });
}
//登录
async function login(req, res) {
    //查找用户
    let result = await mongoose.model(modelName).find(req.body);
    if (result.length > 0) {
        //生成token并返回到前端
        const token = jwt.sign(
            { user: result[0] }, //  用户信息
            'user',  // 密钥，任意字符串
            { expiresIn: 10000 }  //设置有效期,纯数字以秒为单位， 支持字符串 "10 days"  "8h" 
        );

        res.send({
            message: '登录成功',
            code: 200,
            token:"Bearer " + token,
            data: result[0]
        });
    } else {
        //登录失败
        res.send({
            message: '登录失败，用户不存在或输入错误',
            code: -1,
        });
    }
    
}
module.exports = {
    addUser,
    login
};